from flask import Blueprint, request, jsonify, session
from models.User import User
from models.Applicant import Applicant
from models import db

user_bp = Blueprint('user', __name__)

@user_bp.route('/users')
def get_user_info():
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    user = User.query.get(user_id)
    applicant = Applicant.query.filter_by(user_id=user_id).first()
    
    if not user or not applicant:
        return jsonify({'success': False, 'message': '用户不存在'}), 404

    return jsonify({
        'success': True,
        'user': {
            'full_name': applicant.full_name,
            'email': user.email,
            'phone': applicant.phone,
            'expected_position': applicant.expected_position,
            'expected_salary':applicant.expected_salary,
            'work_years': applicant.work_years,
        }
    })

@user_bp.route('/users/update', methods=['POST'])
def update_user_info():
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    data = request.get_json()
    user = User.query.get(user_id)
    applicant = Applicant.query.filter_by(user_id=user_id).first()

    if not user or not applicant:
        return jsonify({'success': False, 'message': '用户不存在'}), 404

    applicant.full_name = data.get('full_name', applicant.full_name)
    user.email = data.get('email', user.email)
    applicant.phone = data.get('phone', applicant.phone)
    if data.get('password'):
        user.password = data['password']  # 更新密码

    db.session.commit()

    return jsonify({
        'success': True,
        'user': {
            'full_name': applicant.full_name,
            'email': user.email,
            'phone': applicant.phone,
            'expected_position': applicant.expected_position,
            'expected_salary': applicant.expected_salary,
        }
    })
